﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace RightControl.Common {
    public class XmlHelper {

        /// <summary>
        /// 反序列化
        /// </summary>
        public static T DESerializer<T>(string strXML) where T : class {
            try {
                using (StringReader sr = new StringReader(strXML)) {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex) {
                return null;
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        public static string XmlSerialize<T>(T obj) {
            using (MemoryStream ms = new MemoryStream()) {
                var setting = new XmlWriterSettings() {
                    Encoding = new UTF8Encoding(false),
                    Indent = true,
                };

                using (XmlWriter writer = XmlWriter.Create(ms, setting)) {
                    XmlSerializer xmlSearializer = new XmlSerializer(obj.GetType());
                    xmlSearializer.Serialize(writer, obj);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
           
            //}
            //        using (StringWriter sw = new StringWriter()) {
            //            //sw.Encoding = Encoding.GetEncoding("utf-8");
            //            Type t = obj.GetType();
            //            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            //            serializer.Serialize(sw, obj);
            //            sw.Close();
            //            return sw.ToString();
            //        }
        }
    }
}
